<template>
    <el-form 
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      ref="RuleformRef"
      :disabled="disable"
      >
      <el-row :gutter='20' style="position: relative;">
        
        <ContentWrapForm  :title="'触发规则'">
          <el-row :gutter='20' style="position: relative;">
            <el-col :span="24">
          <el-form-item >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则名称:" prop="ruleName">
            <el-input  v-model="ruleForm['ruleName']"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专题图模板:" prop="templateName">
            <el-select v-model="ruleForm['templateName']"  placeholder="请选择" style="width: 100%">
                    <el-option-group
                      v-for="group in resultTypeOpt"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option @click="selectTemplate(item)"
                        v-for="item in group.options"
                        :key="item.id"
                        :label="item.templateName"
                        :value="item.id"
                      />
                    </el-option-group>
                  </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="震级范围:" >
            <div  class="flex demo-form-inline">
                  <el-input v-model="ruleForm['magnitude1']"
                  :formatter="(value) =>value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')"
                  :parser="(value) => value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')" 
                  placeholder="请输入" />
                
                      <el-select v-model="ruleForm['magnitude2']"  placeholder="请选择">
                          <el-option
                              v-for="dict in earthQuakeOpt"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
                  <div  class="el-colC">
                    震级
                  </div>
                      <el-select v-model="ruleForm['magnitude3']"  placeholder="请选择">
                          <el-option
                              v-for="dict in earthQuakeOpt1"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
                  <el-input v-model="ruleForm['magnitude4']"
                  :formatter="(value) =>value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')"
                  :parser="(value) => value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')" 
                  placeholder="请输入" />
              </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大烈度范围:" >
            <div  class="flex demo-form-inline">
                  <el-select v-model="ruleForm['intensity1']"  placeholder="请选择">
                          <el-option
                              v-for="dict in intensityOpt"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
                      <el-select v-model="ruleForm['intensity2']"  placeholder="请选择">
                          <el-option
                              v-for="dict in earthQuakeOpt"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
                  <div class="el-colC">
                    烈度
                  </div>
                      <el-select v-model="ruleForm['intensity3']"  placeholder="请选择">
                          <el-option
                              v-for="dict in earthQuakeOpt1"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
                    <el-select v-model="ruleForm['intensity4']"  placeholder="请选择">
                          <el-option
                              v-for="dict in intensityOpt"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地震类型:" prop="earthquakeType">
            <el-checkbox-group v-model="ruleForm['earthquakeType']">
                  <el-checkbox  
                      v-for="dict in earthquakeTypeOpt"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                       />
                </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区域外扩距离:" prop="expansionDistance">
                  <el-input  v-model="ruleForm['expansionDistance']" style="width: 90%;"
                  :formatter="(value) => `${value}`.replace(/[^\d.]/g, '')"
                  :parser="(value) => value.replace(/[^\d.]/g, '')"
                  ></el-input>
                  <div class="el-colC">
                    千米
                  </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="区域范围:" prop="rangeType">
            <el-radio-group v-model="ruleForm['rangeType']">
              <el-radio key="0" :value="'0'" @click="clickClose">上传区域文件</el-radio>
              <el-radio key="1" :value="'1'" @click="clickRadio" >按行政区域选择</el-radio>
            </el-radio-group>
             <ProvinceCity  ref="provinceRef" :regionLists="ruleForm['regionList']"  @querySelect="querySelect"></ProvinceCity>
             <el-col v-if="ruleForm['rangeType']=='1'">
              {{ regionLists }}
             </el-col>
             <el-col :span="24" v-if="ruleForm['rangeType']==0">
                  <UploadFileTo  v-model="ruleForm['list']"  @uploadSuccess="uploadSuccess" />
                </el-col>
                <el-col :span="24" >
                  <div class="mapCard">
                      <LoadMap :fileidInfo="fileidInfo" style="height: 100%" />
                  </div>
              </el-col>
          </el-form-item>
        </el-col>
      </el-row>
      </ContentWrapForm>
       
      <ContentWrapForm  :title="'空间范围规则'"  style="margin-bottom: 72px;width: 100%;">
        <el-row :gutter='20' style="position: relative;">
            <el-col :span="24">
          <el-form-item >
          </el-form-item>
        
        </el-col>
          <el-col v-for="formItem in formColum" :key="formItem.field" :span="formItem.colProps?.span?formItem.colProps?.span:12">
            <el-form-item
            :label="formItem.label" 
            :prop="formItem.field"
            >
            <template #default>
              <el-row v-if="formItem.field === 'rangeRule'" style="width: 100%;">
                <el-col>
                  <el-radio-group v-model="ruleForm['rangeRule']" @change="clickLayer(ruleForm,ruleForm['rangeRule'])">
                    <el-radio key="1" :value="'0'"  >震中扩展范围</el-radio>
                    <el-radio key="2" :value="'1'"  >指定图层扩展</el-radio>
                  </el-radio-group>
                </el-col>
                <el-row v-if="ruleForm['rangeRule'] === '0'" style="width: 100%;">
                  <el-form-item label="震级" prop="magnitude">
                    <el-input v-model="ruleForm['magnitude']" 
                      @input="(value) => value.replace(/[^0-9.]/g, '').replace(/^(\d+\.\d{0,1}).*$/, '$1')"
                      placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="扩展范围" prop="extendedRange">
                    <el-col :span="18">
                      <el-input  v-model="ruleForm['extendedRange']"
                      :formatter="(value) => `${value}`.replace(/\D/g,'')"
                      :parser="(value) => value.replace(/\D/g,'')"
                      ></el-input>
                    </el-col>
                    <el-col :span="6">
                      千米
                    </el-col>
                  </el-form-item>
                  <el-form-item label="间隔距离" prop="intervalDistance">
                    <el-col :span="18">
                    <el-input  v-model="ruleForm['intervalDistance']"
                    :formatter="(value) => `${value}`.replace(/\D/g,'')"
                    :parser="(value) => value.replace(/\D/g,'')"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    千米
                  </el-col>
                  </el-form-item>
                  <el-col :span="24">
                    示例：震级≤5.0，震中上下各扩100Km；震级＞5.0，震中上下再扩100Km基础上每增加0.1震级，上下各增加10Km。
                  </el-col>
                </el-row>
                <el-row v-if="ruleForm['rangeRule'] === '1'" style="width: 100%;">
                  <el-col :span="12">
                    <el-form-item label="图层选择" prop="layerType">
                      <el-select v-model="ruleForm['layerType']" clearable  placeholder="请选择">
                          <el-option 
                              v-for="dict in layerTypeOpt"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="扩展范围" prop="extendedRange">
                    <el-col :span="18">
                      <el-input  v-model="ruleForm['extendedRange']"
                      :formatter="(value) => `${value}`.replace(/\D/g,'')"
                      :parser="(value) => value.replace(/\D/g,'')"
                      ></el-input>
                    </el-col>
                    <el-col :span="6">
                      千米
                    </el-col>
                  </el-form-item>
                  </el-col>
                  <template v-if="ruleForm['layerType'] === '1' && ruleForm['rangeRule'] === '1'" style="width: 100%;">
                    <el-col :span="12" style="margin-top: 12px;">
                    <el-form-item label="烈度" prop="intensityType">
                      <el-select v-model="ruleForm['intensityType']"  placeholder="请选择">
                          <el-option 
                              v-for="dict in intensityTypeOpt"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                        </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" style="margin-top: 12px;">
                  <el-form-item label="未达烈度扩展范围" prop="noExtendedRange">
                    <el-col :span="18">
                      <el-input  v-model="ruleForm['noExtendedRange']"
                      :formatter="(value) => `${value}`.replace(/\D/g,'')"
                      :parser="(value) => value.replace(/\D/g,'')"
                      ></el-input>
                    </el-col>
                    <el-col :span="6">
                      千米
                    </el-col>
                  </el-form-item>
                  </el-col>
                  </template>
                </el-row>
              </el-row>
              <el-input v-else v-model="ruleForm[formItem.field]"></el-input>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      </ContentWrapForm>
      </el-row>
    </el-form>

    <div class="el-colfoot">
      <el-button :disabled="formLoading" type="primary" @click="submitForm" v-if="!disable">确 定</el-button>
      <el-button @click="setClose">取 消</el-button>
    </div>
  <!-- </Dialog> -->
</template>
<script lang="ts" setup>
import * as ftpApi from '@/api/productmange/imgProduce'
import { allSchemas, rules, formColum,earthquakeTypeOpt } from './filesRelease.data'
import UploadFileTo from '@/views/responseLevel/populationDensity/create/UploadFile.vue'
import ProvinceCity from '@/views/responseLevel/populationDensity/create/provinceCity.vue'
import { intensityTypeOpt,intensityOpt } from '../indexData';
import LoadMap from '@/views/earthquake/earthquakeServer/gis/LoadMap.vue'
defineOptions({ name: 'FilesReleaseForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const RuleformRef = ref() // 表单 Ref
const ruleForm:any = ref({
  "ruleName": '', //"规则名称",
  "templateName":'',// "模板名称", 
  "templateId":'',// "模板ID", 
  "magnitude1":'',// "震级范围", 
  "magnitude2":'0',// "震级范围 符号", 
  "magnitude3":'0',// "震级范围 符号", 
  "magnitude4":'',// "震级范围", 
  "intensity1":'',// "烈度范围", 
  "intensity2":'0',// "烈度范围 符号", 
  "intensity3":'0',// "烈度范围 符号", 
  "intensity4":'',// "烈度范围", 
  "earthquakeType":[],// "地震类型", 
  "rangeType":'0',
  list:[],
  regionList:[],
  "expansionDistance":'',// "区域外扩距离", 
  "rangeRule":'0',// "空间范围规则（0：震中扩展范围、1：指定图层扩展）", 
  "magnitude":'',// "震级", 
  "extendedRange":'',// "扩展范围", 
  "intervalDistance":'',// "间隔距离", 
  "layerType":'',// "图层选择 1:影响场2：历史地震3：震中距", 
  "intensityType":'',// "烈度", 
  "noExtendedRange":'',// "未达烈度扩展范围" 
})
const earthQuakeOpt = ref([
  {label:'≤',value:'0'},
  {label:'<',value:'1'},
])
const earthQuakeOpt1 = ref([
  {label:'≤',value:'0'},
  {label:'<',value:'1'},
  {label:'=',value:'2'},
])
const layerTypeOpt = ref( [
    {
      label: '影响场',
      value:'1'
    },
    {
      label: '历史地震',
      value:'2'
    },
    {
      label: '震中距',
      value:'3'
    }
])

const provinceRef = ref()
const regionList = ref([])
const voList = ref()
const regionLists = ref('')

const fileidInfo = ref({
  fileid: '',
  type: 0,
  xzqh:[],
  query: {
    tableName: '',
    fields: '',
    // owner:"private"
  }
})
const reset = () => {
  ruleForm.value = {
  "ruleName": '', //"规则名称",
  "templateName":'',// "模板名称", 
  "templateId":'',// "模板ID", 
  "magnitude1":'',// "震级范围", 
  "magnitude2":'0',// "震级范围 符号", 
  "magnitude3":'0',// "震级范围 符号", 
  "magnitude4":'',// "震级范围", 
  "intensity1":'',// "烈度范围", 
  "intensity2":'0',// "烈度范围 符号", 
  "intensity3":'0',// "烈度范围 符号", 
  "intensity4":'',// "烈度范围", 
  "earthquakeType":[],// "地震类型", 
  "rangeType":'0',
  list:[],
  regionList:[],
  "expansionDistance":'',// "区域外扩距离", 
  "rangeRule":'0',// "空间范围规则（0：震中扩展范围、1：指定图层扩展）", 
  "magnitude":'',// "震级", 
  "extendedRange":'',// "扩展范围", 
  "intervalDistance":'',// "间隔距离", 
  "layerType":'',// "图层选择 1:影响场2：历史地震3：震中距", 
  "intensityType":'',// "烈度", 
  "noExtendedRange":'',// "未达烈度扩展范围" 
}
regionLists.value = ''
regionList.value = []
}
/** 打开弹窗 */
const disable = ref(false)
const open = async (type: string, id?: number|string) => {
  disable.value = type=='view'
  ruleForm.value.regionList = [];
   if (type == 'update'||type == 'view' ) {
    fileidInfo.value.type = 1
    fileidInfo.value.fileid = id
    fileidInfo.value.query.tableName = 'pn_region_common'
    fileidInfo.value.query.fields = 'id,rule_id,province,city,del_flag,create_user,update_user,update_user,create_time'
    fileidInfo.value.query.filter = `rule_id='${id}'`
  } else {
    fileidInfo.value.type = 0
    fileidInfo.value.fileid = ''
    fileidInfo.value.query.tableName = 'temp_file_data'
    fileidInfo.value.query.fields = 'id'
  }
  
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    (await RuleformRef.value).resetFields()
    reset()
    try {
      const data = await ftpApi.getByIdpictureRule({id:id})
      if (data.regionList && data.regionList.length > 0) {
        let datas: any = []
        data.regionList.forEach((item) => {
          if (item.city) {
            datas.push(item.province + '-' + item.city)
          } else {
            datas.push(item.province)
          }
        })
        regionLists.value = datas.join(',')
      } else {
        data.regionList = []
      }
      regionList.value=data.regionList
      data.earthquakeType= data.earthquakeType.split(',');
      ruleForm.value={...data}
    } finally {
      formLoading.value = false
    }
  }else{
    (await RuleformRef.value).resetFields()
    reset()
  }
  await getTemplateList();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
/**
 * 
 * isTest  是否是测试群(0是  1否 )
 * type   类型 (0企业微信  1钉钉)
 * isUse  是否启用(0是  1否)
 */
const emit = defineEmits(['success','setClose']) // 定义 success 事件，用于操作成功后的回调
const setClose=()=>{
  dialogVisible.value = false
  emit('setClose')
}
const submitForm = async () => {
  // 校验表单
  if (!RuleformRef) return
  const valid = await RuleformRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data:any = {...ruleForm.value};
     data.earthquakeType=data.earthquakeType.join(',')
     data.regionList=regionList.value;
    if (formType.value === 'create') {
      await ftpApi.savepictureRule(data)
      message.success(t('common.createSuccess'))
    } else {
      await ftpApi.savepictureRule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    setClose()
  } finally {
    formLoading.value = false
  }
}

const clickRadio = () => {
  if(disable.value) return;
  provinceRef.value.open();
  console.log('allSchemas.formSchema',allSchemas.formSchema);

}

const clickClose = ()=>{
  if(disable.value) return;
  provinceRef.value?.close()
}
const querySelect=(value)=>{
  ruleForm.value.regionList=value;
  regionList.value = value
 var cityArr: any = [];
 let datas: any = []
  value.forEach((item) => {
    if (item.city) {
      datas.push(item.province + '-' + item.city);
      cityArr.push({
        code:item.code,
        name:item.city,
        type:3
      });
    } else {
      datas.push(item.province)
      if(item.province == "全国"){
         cityArr.push({
        code:"",
        name:item.province,
        type:1
      });
      return
      }
      if(item.code){
      cityArr.push({
              code:item.code,
              name:item.province,
              type:2
            });
      }
       
    }
  })
  regionLists.value = datas.join(',')
    fileidInfo.value.type = 2;
     fileidInfo.value.fileid = Date.now() +"";
    fileidInfo.value.xzqh = cityArr;
   
}
// 上传成功
const uploadSuccess = (value) => {
  ruleForm.value.list = value;

     fileidInfo.value.type = 0
    fileidInfo.value.query.tableName = 'temp_file_data'
    fileidInfo.value.query.fields = 'id'
      fileidInfo.value.query.filter = `id='${value[0].id}'`
  fileidInfo.value.fileid = value[0].id
}
const rangeRule0=ref([
{
    label: '震级',
    field: 'magnitude',
    colProps:{
        span:8
      }
  },
  {
    label: '扩展范围',
    field: 'extendedRange',
    colProps:{
        span:8
    }
  },
  {
    label: '间隔距离',
    field: 'intervalDistance',
    colProps:{
      span:8
    },
  },
])
const rangeRule1=ref([
{
    label: '图层选择',
    field: 'layerType',
    isSearch: false,
    isTable:false,
    form:{
      component: 'Select',
      componentProps: {
          options: [
            {
              label: '影响场',
              value:1
            },
            {
              label: '历史地震',
              value:2
            },
            {
              label: '震中距',
              value:3
            }
        ]
      }
    },
  },
  {
    label: '扩展范围',
    field: 'extendedRange',
    isSearch: false,
    isTable:false,
  },
])
const layerType1=[
{
    label: '烈度',
    field: 'intensityType',
    isSearch: false,
    isTable:false,
    form: {
      component: 'Select',
      componentProps: {
          options: intensityTypeOpt
      }
    }
  },
  {
    label: '未达烈度扩展范围',
    field: 'noExtendedRange',
    isSearch: false,
    isTable:false,
  },
]
//添加图层选择项
const clickLayer= async (addformType,type)=>{
 addformType.layerType=''
}
//添加图层选择项
const addLayerForm= async (addformType,type)=>{
  if(type=='影响场'){
    addformType.forEach( async (item)=>{
    await addSchema(item)
  })
  }else{
    addformType.forEach( async (item)=>{
      await delRadioForm(item.field)
    })
  }
}

//添加空间范围数据
const addRadioForm= async (addformType,deldata)=>{
  
  addLayerForm(layerType1,'')
  deldata.forEach( async (item)=>{
    await delRadioForm(item.field)
  })
  addformType.forEach( async (item)=>{
    await addSchema(item)
  })
}
const delRadioForm= async (addformType)=>{
  await delSchema(addformType)
}
//添加Form选项
const addSchema= async (data:any)=>{
  const num =allSchemas.formSchema.length;
  
console.log('allSchemas.formSchema.findIndex(data)',num,);

  if(allSchemas.formSchema.indexOf(data) == -1){
      RuleformRef.value.addSchema(data,num)
  }
}
//删除Form选项
const delSchema= async (val)=>{
  RuleformRef.value.delSchema(val)
}
const resultTypeOpt:any = ref([
{
    label:'公用',
    options:[]
  },
  {
    label:'专用',
    options:[]
  }
]) // 弹窗的标题

const getTemplateList = async()=>{
  const res= await ftpApi.pictureTemplateTwoList();
  const opt=[
  {
      label:'公用',
      options:res.publicList
    },
    {
      label:'专用',
      options:res.privateList
    }
  ]

  resultTypeOpt.value=opt;
  console.log('getTemplateList',res);
  
}
//选择模板
const selectTemplate= async (val)=>{
  ruleForm.value.templateName=val.templateName;
  ruleForm.value.templateId=val.id;
}


</script>

<style scoped>
.mapCard{
  width: 500px;
  height: 500px;
}
.flex{
  display: flex;
  align-items: center;
}
.el-colC {
  text-align: center;
  margin: 0 2px;
}
.demo-form-inline .el-input {
  --el-input-width: 100px;
}

.demo-form-inline .el-select {
  --el-select-width: 90px;
}
</style>